from django import http
from django.conf import settings
from django.shortcuts import render
from alipay import AliPay
from django.views import View

from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RET
from payment.models import Payment


class AlipayView(View):
    def get(self, request, order_id):
        # 取出订单对象
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            return http.HttpResponseForbidden("非法请求")
        # 准备公钥私钥
        app_private_key_string = open(settings.ALIPAY_PRIVATE_KEY).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY).read()
        # 创建alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,  # 支付宝的公钥，验证支付宝回传消息时使用
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是自己的公钥
            sign_type="RSA2",
            debug=False  # 默认False
        )
        # 生成订单字符串
        order_string = alipay.api_alipay_trade_page_pay(out_trade_no=order_id,
                                                        total_amount=str(order.total_amount + order.freight),
                                                        subject="美多商城订单", return_url=settings.ALIPAY_RETURN_URL, )
        # 生成跳转url
        alipay_url = settings.ALIPAY_URL + order_string
        print(alipay_url)
        return http.JsonResponse({"code": RET.OK, "alipay_url": alipay_url})


class PaymentStatusView(View):
    def get(self, request):
        # 获取参数
        dict_data = request.GET.dict()
        sign = dict_data.pop("sign")
        # 校验参数
        app_private_key_string = open(settings.ALIPAY_PRIVATE_KEY).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY).read()
        # 创建alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,  # 支付宝的公钥
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=False
        )
        success = alipay.verify(dict_data, sign)
        if not success:
            return http.HttpResponseForbidden("非法请求")
        # 数据入库
        order_id = dict_data.get("out_trade_no")
        trade_id = dict_data.get("trade_no")
        OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
        # 返回响应
        return render(request, 'pay_success.html', context={"trade_id": trade_id})
